<template>
  <div class="comments-audit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">评论审核管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="fetchPendingComments">刷新数据</el-button>
            <el-button type="danger" @click="confirmDeleteRejected">清理已拒绝评论</el-button>
          </div>
        </div>
      </template>
      
      <!-- 评论列表 -->
      <el-table
        v-loading="loading"
        :data="pendingComments"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="评论内容" min-width="300" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="formatContent(scope.row.content)"></div>
          </template>
        </el-table-column>
        <el-table-column label="评论者" width="120">
          <template #default="scope">
            {{ scope.row.userNickname || '未知用户' }}
          </template>
        </el-table-column>
        <el-table-column label="所属帖子" width="180">
          <template #default="scope">
            <el-tooltip 
              v-if="scope.row.post && scope.row.post.title" 
              :content="scope.row.post.title" 
              placement="top"
            >
              <span class="post-title-text clickable" @click="viewPostDetail(scope.row.post)">
                {{ scope.row.post.title }}
              </span>
            </el-tooltip>
            <span v-else>未知帖子</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="评论时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="附件" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.images && scope.row.images.length > 0" 
              type="primary" 
              link 
              @click="viewAttachments(scope.row.images)"
            >
              查看图片
            </el-button>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewCommentDetail(scope.row)">详情</el-button>
            <el-button type="success" size="small" @click="approveComment(scope.row)">通过</el-button>
            <el-button type="danger" size="small" @click="openRejectDialog(scope.row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 附件查看对话框 -->
    <el-dialog
      v-model="attachmentsDialogVisible"
      title="评论附件"
      width="60%"
    >
      <div class="attachments-container">
        <div v-for="(attachment, index) in currentAttachments" :key="index" class="attachment-item">
          <div v-if="isImage(attachment)">
            <img :src="attachment" class="attachment-image" @click="previewImage(attachment)" />
          </div>
          <div v-else class="file-attachment">
            <el-icon><Document /></el-icon>
            <a :href="attachment" target="_blank">{{ `附件${index + 1}` }}</a>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 拒绝原因对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝评论"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因，将通知给用户"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="rejectComment" :loading="submitting">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="commentDetailDialogVisible"
      title="评论详情"
      width="60%"
    >
      <div v-if="currentCommentDetail" class="comment-detail">
        <div class="comment-meta">
          <span>评论者: {{ currentCommentDetail.userNickname || '未知用户' }}</span>
          <span>评论时间: {{ formatDate(currentCommentDetail.createdAt) }}</span>
        </div>
        
        <div v-if="currentCommentDetail.post" class="post-info">
          <h3>所属帖子信息</h3>
          <div class="post-meta">
            <span>标题: {{ currentCommentDetail.post.title || '未知标题' }}</span>
            <span>作者: {{ currentCommentDetail.post.userNickname || '未知作者' }}</span>
            <span>发布时间: {{ formatDate(currentCommentDetail.post.createdAt) }}</span>
          </div>
          <div class="post-actions">
            <el-button type="primary" size="small" @click="viewPostDetail(currentCommentDetail.post)">查看帖子详情</el-button>
          </div>
        </div>
        
        <div class="comment-content">{{ currentCommentDetail.content }}</div>
        
        <div v-if="currentCommentDetail.images && currentCommentDetail.images.length > 0" class="comment-images">
          <h3>评论图片</h3>
          <div class="images-container">
            <div v-for="(image, index) in currentCommentDetail.images" :key="index" class="image-item">
              <img :src="image" class="detail-image" @click="previewImage(image)" />
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-detail">
        无法加载评论详情
      </div>
    </el-dialog>
    
    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="postDetailDialogVisible"
      title="帖子详情"
      width="70%"
    >
      <div v-if="currentPostDetail" class="post-detail">
        <h2 class="post-title">{{ currentPostDetail.title }}</h2>
        
        <div class="post-meta">
          <span>
            <el-avatar :size="24" :src="currentPostDetail.userAvatar"></el-avatar>
            {{ currentPostDetail.userNickname || '未知用户' }}
          </span>
          <span>发布时间: {{ formatDate(currentPostDetail.createdAt) }}</span>
          <span>类型: {{ getPostTypeText(currentPostDetail.type) }}</span>
          <span>状态: {{ getStatusText(currentPostDetail.status) }}</span>
        </div>
        
        <div class="post-stats">
          <span><el-icon><View /></el-icon> {{ currentPostDetail.viewCount || 0 }}</span>
          <span><el-icon><Star /></el-icon> {{ currentPostDetail.likeCount || 0 }}</span>
          <span><el-icon><ChatDotRound /></el-icon> {{ currentPostDetail.commentCount || 0 }}</span>
        </div>
        
        <div class="post-content">{{ currentPostDetail.content }}</div>
        
        <div v-if="currentPostDetail.images && currentPostDetail.images.length > 0" class="post-images">
          <h3>帖子图片</h3>
          <div class="images-container">
            <div v-for="(image, index) in currentPostDetail.images" :key="index" class="image-item">
              <img :src="image" class="detail-image" @click="previewImage(image)" />
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-detail">
        无法加载帖子详情
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, View, Star, ChatDotRound } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据状态
const loading = ref(false)
const submitting = ref(false)
const pendingComments = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 附件查看相关
const attachmentsDialogVisible = ref(false)
const currentAttachments = ref([])

// 拒绝对话框相关
const rejectDialogVisible = ref(false)
const rejectForm = ref({
  reason: '',
  commentId: null
})

// 评论详情相关
const commentDetailDialogVisible = ref(false)
const currentCommentDetail = ref(null)

// 帖子详情相关
const postDetailDialogVisible = ref(false)
const currentPostDetail = ref(null)

// 获取待审核评论
const fetchPendingComments = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/forum/admin/comments/pending', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    // 添加日志，查看返回的数据格式
    console.log('待审核评论数据格式:', response.data)
    console.log('第一条评论数据:', response.data.comments ? response.data.comments[0] : (Array.isArray(response.data) ? response.data[0] : null))
    
    if (response.data.comments && Array.isArray(response.data.comments)) {
      pendingComments.value = response.data.comments
      total.value = response.data.total || response.data.comments.length
    } else if (Array.isArray(response.data)) {
      pendingComments.value = response.data
      total.value = response.data.length
    } else {
      pendingComments.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error(`获取待审核评论失败: ${error.message || '未知错误'}`)
    console.error('获取待审核评论错误详情:', error)
  } finally {
    loading.value = false
  }
}

// 通过评论
const approveComment = async (comment) => {
  try {
    await axios.patch(`http://localhost:3000/api/forum/admin/comments/${comment.id}/review`, {
      approved: true
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success('评论已通过审核')
    fetchPendingComments() // 刷新列表
  } catch (error) {
    ElMessage.error(`审核评论失败: ${error.message || '未知错误'}`)
  }
}

// 打开拒绝对话框
const openRejectDialog = (comment) => {
  rejectForm.value.commentId = comment.id
  rejectForm.value.reason = ''
  rejectDialogVisible.value = true
}

// 拒绝评论
const rejectComment = async () => {
  if (!rejectForm.value.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  submitting.value = true
  try {
    await axios.patch(`http://localhost:3000/api/forum/admin/comments/${rejectForm.value.commentId}/review`, {
      approved: false,
      rejectReason: rejectForm.value.reason
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success('评论已被拒绝')
    rejectDialogVisible.value = false
    fetchPendingComments() // 刷新列表
  } catch (error) {
    ElMessage.error(`拒绝评论失败: ${error.message || '未知错误'}`)
  } finally {
    submitting.value = false
  }
}

// 查看评论详情
const viewCommentDetail = (comment) => {
  console.log('评论详情数据:', comment)
  currentCommentDetail.value = comment
  commentDetailDialogVisible.value = true
}

// 查看帖子详情
const viewPostDetail = (post) => {
  console.log('帖子详情数据:', post)
  currentPostDetail.value = post
  postDetailDialogVisible.value = true
}

// 查看附件
const viewAttachments = (images) => {
  console.log('评论图片数据:', images)
  currentAttachments.value = images
  attachmentsDialogVisible.value = true
}

// 预览图片
const previewImage = (url) => {
  ElMessageBox.alert('<img src="' + url + '" style="max-width: 100%;" />', '图片预览', {
    dangerouslyUseHTMLString: true,
    showConfirmButton: false,
    callback: () => {}
  })
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchPendingComments()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPendingComments()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化内容（截取前100个字符）
const formatContent = (content) => {
  if (!content) return ''
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText
}

// 判断是否为图片
const isImage = (url) => {
  if (!url) return false
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

// 获取帖子类型文本
const getPostTypeText = (type) => {
  const typeMap = {
    general: '综合',
    technical: '技术',
    question: '问答',
    share: '分享'
  }
  return typeMap[type] || type
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 页面加载时获取数据
onMounted(() => {
  fetchPendingComments()
})

// 删除所有被拒绝的评论
const confirmDeleteRejected = () => {
  ElMessageBox.confirm(
    '确定要删除所有已被拒绝的评论吗？此操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteRejectedComments()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除操作',
      })
    })
}

const deleteRejectedComments = async () => {
  loading.value = true
  try {
    const response = await axios.post('http://localhost:3000/api/forum/admin/comments/delete-rejected', {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success(`成功删除 ${response.data.deletedCount || 0} 条被拒绝的评论`)
    fetchPendingComments() // 刷新列表
  } catch (error) {
    ElMessage.error(`删除被拒绝评论失败: ${error.message || '未知错误'}`)
    console.error('删除被拒绝评论错误详情:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.comments-audit-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.box-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  transition: all 0.3s;
}

.box-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409eff;
  border-radius: 2px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.post-title-text {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.post-title-text.clickable {
  color: #409eff;
  cursor: pointer;
  transition: all 0.3s;
}

.post-title-text.clickable:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 附件样式 */
.attachments-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 10px 0;
}

.attachment-item {
  width: 200px;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.attachment-item:hover {
  transform: translateY(-3px);
}

.attachment-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  object-fit: cover;
  cursor: pointer;
}

.attachment-image:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.file-attachment {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fff;
  transition: all 0.3s;
}

.file-attachment:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.file-attachment a {
  color: #409eff;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  transition: all 0.3s;
}

.file-attachment a:hover {
  color: #66b1ff;
}

/* 评论详情样式 */
.comment-detail {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.comment-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
  background-color: #f9fafc;
  padding: 12px 16px;
  border-radius: 6px;
}

.post-info {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f0f9eb;
  border-radius: 6px;
  border-left: 3px solid #67c23a;
}

.post-info h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #67c23a;
}

.post-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #606266;
  font-size: 14px;
}

.post-actions {
  margin-top: 12px;
}

.comment-content {
  margin-bottom: 24px;
  line-height: 1.8;
  white-space: pre-wrap;
  color: #303133;
  font-size: 15px;
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.comment-images {
  margin-top: 24px;
  background-color: #f9fafc;
  padding: 16px;
  border-radius: 6px;
}

.comment-images h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 600;
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.image-item {
  width: calc(33.33% - 16px);
  margin-bottom: 16px;
  transition: all 0.3s;
}

.image-item:hover {
  transform: scale(1.02);
}

.detail-image {
  width: 100%;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  object-fit: cover;
  cursor: pointer;
}

.detail-image:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.no-detail {
  text-align: center;
  padding: 40px;
  color: #909399;
  font-size: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
}

/* 帖子详情样式 */
.post-detail {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.post-title {
  margin-bottom: 16px;
  color: #303133;
  font-size: 22px;
  font-weight: 600;
  line-height: 1.4;
  text-align: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.post-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  color: #909399;
  font-size: 14px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.post-content {
  margin-bottom: 24px;
  line-height: 1.8;
  white-space: pre-wrap;
  color: #303133;
  font-size: 15px;
  padding: 16px;
  background-color: #f9fafc;
  border-radius: 6px;
}

.post-images {
  margin-top: 24px;
  background-color: #f9fafc;
  padding: 16px;
  border-radius: 6px;
}

.post-images h3 {
  font-size: 16px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 600;
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

/* 表格样式增强 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #303133;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table--border th:first-child) {
  border-left: none;
}

:deep(.el-table--border th:last-child) {
  border-right: none;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f0f5ff !important;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .comment-meta, .post-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .image-item {
    width: calc(50% - 16px);
  }
}

@media screen and (max-width: 768px) {
  .image-item {
    width: 100%;
  }
}
</style>